<template>
  <div class="padding-bottom-10">
    <el-alert title="登记人工工时" type="info" show-icon description="此处可以按照每个用工登记工时"> </el-alert>
    <el-table v-loading="loading" :data="costEmployeeList" class="margin-top-10">
      <el-table-column label="雇员" align="center" prop="employeeId">
        <template #default="{ row }">
          <data-tag :options="taskEmployeeList" :value="row.employeeId" label-name="employeeName" value-name="employeeId" type="notag" />
        </template>
      </el-table-column>
      <el-table-column label="工时" align="center" prop="workingHours" />
      <el-table-column label="开始日期" align="center" prop="workingStart" width="180">
        <template #default="{ row }">
          <span>{{ parseTime(row.workingStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="workingFinish" width="180">
        <template #default="{ row }">
          <span>{{ parseTime(row.workingFinish, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #header>
          <el-tag v-hasPermi="['agriculture:costEmployee:add']" class="cursor-pointer" @click="handleAdd">新增</el-tag>
        </template>
        <template #default="{ row }">
          <el-button v-hasPermi="['agriculture:costEmployee:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)"
            >修改</el-button
          >
          <el-button v-hasPermi="['agriculture:costEmployee:remove']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="雇员" prop="employeeId">
          <el-select v-model="form.employeeId" class="display-block" placeholder="请选择雇员" clearable filterable>
            <el-option v-for="item in taskEmployeeList" :key="item.employeeId" :label="item.employeeName" :value="item.employeeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工时" prop="workingHours">
          <el-input v-model="form.workingHours" placeholder="请输入工时">
            <template #append> 天 </template>
          </el-input>
        </el-form-item>
        <el-form-item label="开始日期" prop="workingStart">
          <el-date-picker
            v-model="form.workingStart"
            class="w100"
            clearable
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="workingFinish">
          <el-date-picker
            v-model="form.workingFinish"
            class="w100"
            clearable
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结束日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CostEmployee" lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listCostEmployee, getCostEmployee, delCostEmployee, addCostEmployee, updateCostEmployee } from '@/api/agriculture/costEmployee';
import { addLog } from '@/api/agriculture/taskLog';
import { listTaskEmployee } from '@/api/agriculture/taskEmployee';

const props = defineProps({
  taskId: {
    type: [Number, String],
    required: true
  }
});

const emit = defineEmits(['log']);

const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const costEmployeeList = ref([]);
const taskEmployeeList = ref([]);
const title = ref('');
const open = ref(false);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  taskId: props.taskId
});

const form = reactive({
  costId: null,
  taskId: props.taskId,
  employeeId: null,
  workingHours: null,
  workingStart: null,
  workingFinish: null,
  remark: null,
  status: '0',
  orderNum: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  delFlag: null
});

const rules = ref({
  employeeId: [{ required: true, message: '雇员ID不能为空', trigger: 'blur' }],
  workingHours: [{ required: true, message: '工时不能为空', trigger: 'blur' }],
  workingStart: [{ required: true, message: '开始日期不能为空', trigger: 'blur' }],
  workingFinish: [{ required: true, message: '结束日期不能为空', trigger: 'blur' }],
  delFlag: [{ required: true, message: '删除标志不能为空', trigger: 'blur' }]
});

const formRef = ref(null);

onMounted(() => {
  getList();
  getTaskEmployeeList();
});

const getList = async () => {
  loading.value = true;
  const response = await listCostEmployee(queryParams);
  costEmployeeList.value = response.rows;
  total.value = response.total;
  loading.value = false;
};

const getTaskEmployeeList = async () => {
  const response = await listTaskEmployee({ taskId: props.taskId });
  taskEmployeeList.value = response.rows;
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  Object.assign(form, {
    costId: null,
    taskId: props.taskId,
    employeeId: null,
    workingHours: null,
    workingStart: null,
    workingFinish: null,
    remark: null,
    status: '0',
    orderNum: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  });
  formRef.value.resetFields();
};

const addTaskLog = async (des) => {
  await addLog({ taskId: props.taskId, operDes: des });
  emit('log');
};

const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加人工工时';
};

const handleUpdate = async (row) => {
  reset();
  const costId = row.costId || ids.value;
  const response = await getCostEmployee(costId);
  Object.assign(form, response.data);
  open.value = true;
  title.value = '修改人工工时';
};

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (form.costId) {
        await updateCostEmployee(form);
        await addTaskLog('修改人工工时');
        ElMessage.success('修改成功');
        open.value = false;
        getList();
      } else {
        await addCostEmployee(form);
        await addTaskLog('新增人工工时');
        ElMessage.success('新增成功');
        open.value = false;
        getList();
      }
    }
  });
};

const handleDelete = (row) => {
  const costIds = row.costId || ids.value;
  ElMessageBox.confirm('是否确认删除人工工时编号为"' + costIds + '"的数据项？')
    .then(async () => {
      await delCostEmployee(costIds);
      getList();
      await addTaskLog('删除人工工时');
      ElMessage.success('删除成功');
    })
    .catch(() => {});
};

const handleExport = () => {
  // Implement export logic here
};
</script>
